$(function(){
    let $title = $("#title");
    let $todolist = $("#todolist");
    let $donelist = $("#donelist");
    
        
 function bindEvent(){
     $title.keydown(function(event){
       
         var code = event.keyCode || event.which;

         if(code === 13){
            add();
     
         }
         var local = getData();
         local.push({ title: $(this).val(), done: false });
         saveData(local);
     })
 
 $todolist.parent().on("change","input[type=checkbox]",toggleList)

 $todolist.on("click","p",edit)

 $todolist.on("blur","input[type=text]",save)
 $todolist.on("click","a",remove)
 load();
}

function add(){
let $todo = $(
    `<li>
     <input type="checkbox">
     <p>${$title.val()}</p>
     <a href="javascript:void(0)"></a>
     </li> `    
);

$todolist.prepend($todo);
$title.val("")
   load();
}


function toggleList(){
 
   if(this.checked){
       $donelist.append($(this).parent());
   }else{
       $todolist.append($(this).parent());
       
   }
   load();
}


function load(){
          

      $("#donecount").text($("#donelist").children().length);
      $("#todocount").text($("#todolist").children().length);
 }
   


function edit(){
  
    if($(this).children().length>0){
    
         return false;
    } 

  var html = $(this).text();

  $(this).html(`<input type="text" value=${html}>`);

  $(this).children().select();
  
}

  function save(){

      let value = $(this).val();
      $(this).parent().html(value); 
  }


 function saveData(data) {
    localStorage.setItem('todolist', JSON.stringify(data));
}



 
  
   function remove(){
       $(this).parent().remove(); 
         load();
   }
   bindEvent();
  
})





 